<?php
class Artist_model extends CI_Model {

    function __construct()
    {
        parent::__construct();
    }
	
	function redirect_artist_name_alias()
	{
		$artist_name_alias = strtolower($this->uri->segment(1));
		if(!empty($artist_name_alias)):
			$is_exist = $this->db->from('artist_info')->where(array('artist_name_alias' => $artist_name_alias))->count_all_results();
			if(!empty($is_exist)):
				$artist_id = $this->db->select('artist_id')
				->get_where('artist_info',array('artist_name_alias' => $artist_name_alias),1)
				->row()->artist_id;
				redirect($artist_url.'summary/'.intval($artist_id), 'location', 301);
			endif;		
		endif;
	}
	
	function ajax_vote_artist()
	{
		$artist_id = $this->input->post('artist_id');
		$score = $this->input->post('score');
		$datetime = date('Y-m-d');
		$dataMember = $this->session->userdata('member');
		if(!empty($dataMember)):
			$member_id = $dataMember['member_id'];
			$is_exist = $this->db->from('artist_rating')->where(array('artist_id' => $artist_id,'member_id' => $member_id))->count_all_results();	
			if(!empty($is_exist)):
				//Output
				$data = array(
					'msg' => 'คุณเคยให้คะแนนศิลปินนี้ไปแล้วค่ะ',
					'avg' => '',
					'people' => ''
				);			
				echo json_encode($data);
			else:
				$data = array(
					'artist_id' => $artist_id,
					'member_id' => $member_id,
					'artist_rating_score' => $score
				);
				//artist_rating
				$this->db->insert('artist_rating',$data);
				//artist_click_stat
				$this->db->set('artist_click_rate', 'artist_click_rate + 1', FALSE);
				$this->db->where(array('artist_id' => $artist_id,'update_date' => $datetime));
				$this->db->update('artist_click_stat');
				//artist
				$avg = $this->db->select('SUM(artist_rating_score)/COUNT(artist_rating_score) as Avg')->group_by('artist_id')->get_where('artist_rating',array('artist_id' => $artist_id))->row()->Avg;
				$this->db->update('artist',array('rate_score' => $avg),array('artist_id' => $artist_id));
				//Output
				$data = array(
					'msg' => 'ให้คะแนนศิลปินนี้เรียบร้อยแล้วค่ะ',
					'avg' => number_format($avg,2),
					'people' => $this->db->from('artist_rating')->where(array('artist_id' => $artist_id))->count_all_results()
				);
				echo json_encode($data);
			endif;		
		else:
			//Output
			$data = array(
				'msg' => 'กรุณาล๊อคอินก่อนโหวตคะแนนค่ะ',
				'avg' => '',
				'people' => ''
			);			
			echo json_encode($data);		
		endif;
		exit;
	}
}

?>